/**
 * @author YinHang
 * Widget
 */
;(function () {
	/**
	 * uri
	 * path
	 * parent
	 * id
	 */
	function Widget(params) {
		this._params = params;
		this.reload();
	};
	
	//重新载入 widget(ui&数据 )
	Widget.prototype.reload = function () {
		var wthis = this;
		//获取metadata.xml
		wthis.getMetadata(function () {
			//获取初始化数据
			wthis.getInitData(function (initData) {
				//加载样式文件
				oacore.Util.getCssList(wthis.getStyleFileList());
				//加载预处理脚本
				oacore.Util.loadScriptQueue(wthis.getInitScriptQueueUris(), function () {
					var dialog = $("<div>");
					//加载对话框模板
					oacore.UI.render("widget/widget", {title: wthis.getName(), width: "100%", height: wthis.getHeight()}, dialog, function () {
						//加载内容模板
						var content = dialog.find("div.widget-content:first");
						oacore.UI.render(wthis.getFace(), initData, content, function () {
							$(wthis._params.parent).empty().removeClass("loading").append(dialog);
							//关闭事件
							dialog.find("span.widget-op-exit:first").bind("click", function () {
								if(wthis._params.widgetExit)
									if(wthis._params.widgetExit(wthis._params.id) != false)
										wthis.exit();
							});
							//加载后期处理脚本
							oacore.Util.loadScriptQueue(wthis.getMainScriptQueueUris());
						}, {filter_data: false});
					});
				});
			});
		});
	};
	
	Widget.prototype.exit = function () {
		this._params.parent.remove();
	};
	
	//取得初始化数据
	Widget.prototype.getInitData = function (callback) {
		var wthis = this;
		var uri = wthis.getUriListFromMetadata("init-javascripts data-javascript")[0];
		if(uri)
		{
			$.util.Data.request({
				url: uri,
				dataType: "text",
				buffer: true,
				cache: true,
				success: function (data) {
					((new Function(data))())(callback);
				}
			});
		}
		else
		{
			callback({});
		}
	};
	
	//取得xml节点(metadata)中的uri列表，以","分割为标志.
	Widget.prototype.getUriListFromMetadata = function (selector) {
		var uriList = [];
		var params = this._params;
		var nodeList = this.getDatasFromMetadata(selector);
		var nodeListLen = nodeList.length;
		for(var i=0;i<nodeListLen;++i)
		{
			var sectionUris = nodeList[i].split(",");
			var sectionUrisLength = sectionUris.length;
			for(var j=0;j<sectionUrisLength;++j)
				uriList.push(params.path + params.uri + $.trim(sectionUris[j]));
		}
		return uriList;
	};
	
	//取得后期处理脚本加载uri队列
	Widget.prototype.getMainScriptQueueUris = function () {
		return this.getUriListFromMetadata("main-javascript-queue");
	};
	
	//取得前期处理脚本加载uri队列
	Widget.prototype.getInitScriptQueueUris = function () {
		return this.getUriListFromMetadata("init-javascripts program-javascript-queue");
	};
	
	//取得样式文件列表
	Widget.prototype.getStyleFileList = function () {
		return this.getUriListFromMetadata("style-files");
	};
	
	//取得内容模板
	Widget.prototype.getFace = function () {
		return this._params.uri + this.getDatasFromMetadata("face")[0];
	};
	
	Widget.prototype.getDatasFromMetadata = function (selector) {
		var nodeList = this.getNodesFromMetadata(selector);
		var nodeDataList = [];
		var nodeListLen = nodeList.length;
		for(var i=0;i<nodeListLen;++i)
		{
			if(nodeList[i].childNodes[0])
			{
				var value = $.trim(nodeList[i].childNodes[0].nodeValue);
				if(value && value.length > 0)
					nodeDataList.push(value);
			}
		}
		return nodeDataList;
	};
	
	//Metadata XmlDom节点选择器
	Widget.prototype.getNodesFromMetadata = function (selector) {
		return $.util.xmlDomSelector(this.metadata, selector);
	};
	
	Widget.prototype.getHeight = function () {
		return this.get("height");
	};
	
	Widget.prototype.getWidth = function () {
		return this.get("width");
	};
	
	Widget.prototype.getName = function () {
		return this.get("name");
	};
	
	Widget.prototype.get = function (attr) {
		return this.entity.getAttribute(attr);
	};
	
	//获取metadata
	Widget.prototype.getMetadata = function (callback) {
		var wthis = this;
		$.util.Data.request({
			url: wthis._params.path + wthis._params.uri + "/" + "metadata.xml",
			dataType: "xml",
			buffer: true,
			cache: true,
			success: function (data) {
				wthis.metadata = data;
				wthis.entity = wthis.getNodesFromMetadata("widget")[0];
				if(callback)
					callback();
			}
		});
	};
	
	window.Widget = Widget;
})();

/**
 * @author YinHang
 * Widget System
 */
;(function () {
	/**
	 * parent
	 * rows
	 * path
	 * positionUpdate
	 * widgetExit
	 */
	function WidgetSystem(params) {
		this._params = params;
		this.makeSortGrid();
		if(!this._params.parent)
			return null;
	};
	
	/**
	 * 生成插架系统的容器
	 * @return
	 */
	WidgetSystem.prototype.makeSortGrid = function () {
		this.wsDiv = $("<div>").addClass("widget-system");
		var wsthis = this;
		for(var i=0;i<this._params.rows;++i)
		{
			$("<ul>")
			.addClass("ws-sortable")
			.attr("id", "row_" + ( i + 1 ))
			.appendTo(this.wsDiv);
		}
		this.wsDiv.find("ul.ws-sortable").sortable({
			connectWith: "ul.ws-sortable",
			handle: "div.widget-topbar",
			placeholder: "widget-sort-placeholder"
		})
		.bind("sortupdate", function (event, ui) {
			wsthis.updatePosition(ui.item.parents("ul.ws-sortable:first"));
		})
		.bind("sort", function (event, ui) {
			ui.placeholder.height(ui.item.height());
		});
		$(this._params.parent).append(this.wsDiv);
	};
	
	/**
	 * 更新一列下所有小件的位置
	 * @param ul
	 * @return
	 */
	WidgetSystem.prototype.updatePosition = function (ul) {
		var wsthis = this;
		var row = ul.attr("id").split("_")[1];
		ul.children("li.ws-sortable-li").each(function (i) {
			var $this = $(this);
			var newPostion = i + 1;
			$this.attr("id", "position_" + newPostion);
			if(wsthis._params.positionUpdate)
				wsthis._params.positionUpdate($this.data("widgetId"), row, newPostion);
		});
	};
	
	/**
	 * 将一个小件添加进系统
	 * @param widgetMetadta
	 * @return
	 */
	WidgetSystem.prototype.addToSystem = function (widgetMetadta) {
		var targetLi = $("<li>").appendTo("#row_" + widgetMetadta.row).attr("id", "position_" + widgetMetadta.position).addClass("ws-sortable-li loading").data("widgetId", widgetMetadta.id);
		var wsthis = this;
		new Widget({
			path: wsthis._params.path,
			uri: widgetMetadta.uri,
			parent: targetLi,
			id: widgetMetadta.id,
			widgetExit: wsthis._params.widgetExit
		});
	};
	
	/**
	 * 按照列表渲染所有小件
	 * 
	 */
	WidgetSystem.prototype.render = function (widgetList) {
		//排序用数组
		var sortedList = [];
		for(var i=0;i<this._params.rows;++i)
			sortedList.push([]);
		//将widget元数据加入排序数组
		var wlLen = widgetList.length;
		for(var i=0;i<wlLen;++i)
			sortedList[widgetList[i].row - 1].push(widgetList[i]);
		function sortBy(a, b) {
			return a.position - b.position;
		};
		//排序&生成
		for(var i=0;i<this._params.rows;++i)
		{
			sortedList[i].sort(sortBy);
			var widgetNum = sortedList[i].length;
			for(var j=0;j<widgetNum;++j)
			{
				var newWidgetMetadta = sortedList[i][j];
				this.addToSystem(newWidgetMetadta);
			}
		}
	};
	
	window.WidgetSystem = WidgetSystem;
})();